/**
 * @file dataPool.c
 * @author your name (you@domain.com)
 * @brief 管理一个数据池，提供数据块的分配和释放功能
 * @version 0.1
 * @date 2025-09-25
 * 
 * @copyright Copyright (c) 2025
 * 
 */
#include "dataPool.h"
#include "cmsis_os2.h"
#include "SEGGER_RTT.h"

uint8_t data_pool[DATA_POOL_NUM][DATA_POOL_SIZE];
typedef struct{
    uint8_t(* pool)[DATA_POOL_SIZE];
    uint8_t num;
    uint16_t size;
    osMessageQueueId_t queue;
}DataPoolHeadle;
DataPoolHeadle dataPoolHeadle;

void dataPool_init(){
    dataPoolHeadle.pool = data_pool;
    dataPoolHeadle.size = DATA_POOL_SIZE;
    dataPoolHeadle.num = DATA_POOL_NUM;
    const osMessageQueueAttr_t dataPool_queueAttr = {.name = "dataPoolQueue"};
    dataPoolHeadle.queue = osMessageQueueNew(DATA_POOL_NUM, sizeof(uint8_t(*)[DATA_POOL_SIZE]), &dataPool_queueAttr);
    if(dataPoolHeadle.queue==NULL) SEGGER_RTT_WriteString(0,"dataPool_queueError\r\n");
    for(uint8_t i=0; i<DATA_POOL_NUM; i++){
        uint8_t* ptr = dataPoolHeadle.pool[i];
        osMessageQueuePut(dataPoolHeadle.queue, &ptr, 0, 0);
    }
}
uint8_t* dataPool_get(uint32_t timeout){
    uint8_t* p = NULL;
    if(osMessageQueueGet(dataPoolHeadle.queue, &p, NULL, timeout) == osOK){
        return p;
    }
    return NULL;
}
void dataPool_free(uint8_t* p){
    osMessageQueuePut(dataPoolHeadle.queue, &p, 0, 0);
}